import React, { useState, useEffect, useRef } from 'react';
import { 
  Card, 
  Input, 
  Button, 
  List, 
  Typography, 
  Space, 
  Modal,
  Spin,
  Empty,
  Tooltip,
  message
} from 'antd';
import { 
  SendOutlined, 
  PlusOutlined, 
  DeleteOutlined,
  CloseOutlined,
  RobotOutlined,
  UserOutlined,
  ReloadOutlined,
  MessageOutlined
} from '@ant-design/icons';
import { marked } from 'marked';
import hljs from 'highlight.js';
import 'highlight.js/styles/github-dark.css';
// 注册常用语言
import javascript from 'highlight.js/lib/languages/javascript';
import python from 'highlight.js/lib/languages/python';
import java from 'highlight.js/lib/languages/java';
import cpp from 'highlight.js/lib/languages/cpp';
import css from 'highlight.js/lib/languages/css';
import html from 'highlight.js/lib/languages/xml';
import json from 'highlight.js/lib/languages/json';
import sql from 'highlight.js/lib/languages/sql';
import bash from 'highlight.js/lib/languages/bash';
import typescript from 'highlight.js/lib/languages/typescript';
import ragService from '../../services/rag';
import './ChatPanel.css';

const { TextArea } = Input;
const { Text, Paragraph } = Typography;

// 注册highlight.js语言
hljs.registerLanguage('javascript', javascript);
hljs.registerLanguage('python', python);
hljs.registerLanguage('java', java);
hljs.registerLanguage('cpp', cpp);
hljs.registerLanguage('css', css);
hljs.registerLanguage('html', html);
hljs.registerLanguage('xml', html);
hljs.registerLanguage('json', json);
hljs.registerLanguage('sql', sql);
hljs.registerLanguage('bash', bash);
hljs.registerLanguage('shell', bash);
hljs.registerLanguage('typescript', typescript);

// 配置 marked 和代码高亮
const renderer = new marked.Renderer();

// 自定义代码块渲染
renderer.code = function(code, language) {
  const validLanguage = language && hljs.getLanguage(language) ? language : 'text';
  let highlightedCode;
  
  try {
    if (validLanguage !== 'text') {
      highlightedCode = hljs.highlight(code, { language: validLanguage }).value;
    } else {
      highlightedCode = hljs.highlightAuto(code).value;
    }
  } catch (err) {
    highlightedCode = code;
  }

  // 生成唯一ID用于复制功能
  const codeId = 'code-' + Math.random().toString(36).substr(2, 9);

  return `
    <div class="code-block-wrapper">
      <div class="code-block-header">
        <span class="code-language">${validLanguage}</span>
        <button class="copy-code-btn" data-code-id="${codeId}" data-code="${encodeURIComponent(code)}">
          复制
        </button>
      </div>
      <pre><code id="${codeId}" class="hljs language-${validLanguage}">${highlightedCode}</code></pre>
    </div>
  `;
};

marked.setOptions({
  renderer: renderer,
  breaks: true,
  gfm: true
});

const ChatPanel = ({
  threads,
  currentThread,
  onThreadChange,
  onCreateThread,
  onDeleteThread,
  onRefreshThreads,
  onClose,
  loading
}) => {
  const [messages, setMessages] = useState([]);
  const [inputMessage, setInputMessage] = useState('');
  const [sending, setSending] = useState(false);
  const [loadingHistory, setLoadingHistory] = useState(false);
  const [currentStreamingMessage, setCurrentStreamingMessage] = useState('');
  const [streamingSources, setStreamingSources] = useState([]);
  const messagesEndRef = useRef(null);
  const inputRef = useRef(null);

  // 添加调试信息
  useEffect(() => {
  }, [threads, onDeleteThread, currentThread]);

  // 当前线程变化时加载聊天历史
  useEffect(() => {
    if (currentThread) {
      loadChatHistory();
    } else {
      setMessages([]);
    }
  }, [currentThread]);

  // 自动滚动到底部
  useEffect(() => {
    scrollToBottom();
  }, [messages, currentStreamingMessage]);

  // 处理代码复制功能
  useEffect(() => {
    const handleCopyClick = async (e) => {
      if (e.target.classList.contains('copy-code-btn')) {
        const code = decodeURIComponent(e.target.getAttribute('data-code'));
        try {
          await navigator.clipboard.writeText(code);
          const originalText = e.target.textContent;
          e.target.textContent = '已复制';
          e.target.style.background = 'rgba(34, 197, 94, 0.2)';
          e.target.style.color = '#22c55e';
          setTimeout(() => {
            e.target.textContent = originalText;
            e.target.style.background = 'rgba(255, 255, 255, 0.1)';
            e.target.style.color = '#ccc';
          }, 2000);
          message.success('代码已复制到剪贴板');
        } catch (err) {
          message.error('复制失败');
        }
      }
    };

    document.addEventListener('click', handleCopyClick);
    return () => {
      document.removeEventListener('click', handleCopyClick);
    };
  }, []);

  // 滚动到消息底部
  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  };

  // 加载聊天历史
  const loadChatHistory = async () => {
    if (!currentThread) return;
    
    try {
      setLoadingHistory(true);
      const response = await ragService.getChatHistory(currentThread.threadId);
      if (response.data.code === 200) {
        let historyData;
        if (typeof response.data.data === 'string') {
          historyData = JSON.parse(response.data.data);
        } else {
          historyData = response.data.data;
        }
        
        const history = historyData.history || [];
        setMessages(history);
      }
    } catch (error) {
      message.error('加载聊天历史失败');
    } finally {
      setLoadingHistory(false);
    }
  };

  // 发送消息
  const sendMessage = async () => {
    if (!inputMessage.trim() || sending || !currentThread) return;

    const userMessage = inputMessage.trim();
    setInputMessage('');
    setSending(true);
    setCurrentStreamingMessage('');
    setStreamingSources([]);

    // 添加用户消息到界面
    const newUserMessage = {
      role: 'user',
      content: userMessage,
      sentAt: Math.floor(Date.now() / 1000)
    };
    setMessages(prev => [...prev, newUserMessage]);

    let finalStreamingMessage = '';
    let finalStreamingSources = [];

    try {
      // 开始流式聊天
      await ragService.streamChat(
        currentThread.threadId,
        userMessage,
        // onMessage callback
        (data) => {
          if (data.textResponse) {
            finalStreamingMessage += data.textResponse;
            setCurrentStreamingMessage(finalStreamingMessage);
          }
          if (data.sources && data.sources.length > 0) {
            finalStreamingSources = data.sources;
            setStreamingSources(data.sources);
          }
        },
        // onError callback
        (error) => {
          message.error(`发送消息失败: ${error}`);
          setSending(false);
          setCurrentStreamingMessage('');
        },
        // onComplete callback
        () => {
          // 将流式消息添加到消息列表
          if (finalStreamingMessage) {
            const assistantMessage = {
              role: 'assistant',
              content: finalStreamingMessage,
              sources: finalStreamingSources,
              sentAt: Math.floor(Date.now() / 1000)
            };
            setMessages(prev => [...prev, assistantMessage]);
          }
          
          setSending(false);
          setCurrentStreamingMessage('');
          setStreamingSources([]);
          
          // 聚焦输入框
          setTimeout(() => {
            inputRef.current?.focus();
          }, 100);
        }
      );
    } catch (error) {
      message.error('发送消息失败');
      setSending(false);
      setCurrentStreamingMessage('');
    }
  };

  // 处理输入框回车
  const handleKeyPress = (e) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      sendMessage();
    }
  };

  // 创建新线程
  const handleCreateThread = async () => {
    try {
      // 使用原生prompt获取线程名称
      const threadName = prompt('请输入对话名称（可选，留空则自动生成）:', '');
      
      // 用户点击取消时，prompt返回null
      if (threadName === null) {
        return;
      }
      
      // 处理输入的名称（去除首尾空格）
      const trimmedName = threadName.trim();
      
      // 显示加载状态
      const hide = message.loading('正在创建对话...', 0);
      
      // 调用创建函数
      await onCreateThread(trimmedName);
      
      // 隐藏加载状态
      hide();
      
      message.success('创建新对话成功');
    } catch (error) {
      message.error('创建新对话失败');
    }
  };

  // 处理删除按钮点击 - 直接删除版本
  const handleDeleteClick = async (e, threadId) => {
    // 阻止事件冒泡
    e.preventDefault();
    e.stopPropagation();
    
    try {
      if (!onDeleteThread) {
        throw new Error('onDeleteThread 函数未定义');
      }
      
      if (typeof onDeleteThread !== 'function') {
        throw new Error('onDeleteThread 不是一个函数');
      }
      
      // 显示加载状态
      const hide = message.loading('正在删除对话...', 0);
      
      // 调用删除函数
      const result = await onDeleteThread(threadId);
      
      // 隐藏加载状态
      hide();
      
      message.success('删除对话成功');
      
    } catch (error) {
      message.error(`删除对话失败: ${error.message || error}`);
    }
  };

  // 渲染消息
  const renderMessage = (message, index) => {
    const isUser = message.role === 'user';
    const time = new Date(message.sentAt * 1000).toLocaleTimeString();

    return (
      <div key={index} className={`message ${isUser ? 'user' : 'assistant'}`}>
        <div className="message-avatar">
          {isUser ? <UserOutlined /> : <RobotOutlined />}
        </div>
        <div className="message-content">
          <div className="message-text">
            {isUser ? (
              <Paragraph copyable={{ text: message.content }}>
                {message.content}
              </Paragraph>
            ) : (
              <div 
                className="markdown-content"
                dangerouslySetInnerHTML={{ 
                  __html: marked.parse(message.content || '') 
                }}
              />
            )}
          </div>
          <div className="message-time">
            <Text type="secondary" style={{ fontSize: '11px' }}>{time}</Text>
          </div>
        </div>
      </div>
    );
  };

  // 头部组件
  const renderHeader = () => (
    <div className="chat-header">
      <Space>
        <RobotOutlined />
        <span>AI助手</span>
      </Space>
      <Space>
        <Tooltip title="刷新对话列表">
          <Button 
            type="text" 
            size="small" 
            icon={<ReloadOutlined />}
            onClick={onRefreshThreads}
            loading={loading}
          />
        </Tooltip>
        <Tooltip title="新建对话">
          <Button 
            type="text" 
            size="small" 
            icon={<PlusOutlined />}
            onClick={handleCreateThread}
          />
        </Tooltip>
        <Button 
          type="text" 
          size="small" 
          icon={<CloseOutlined />}
          onClick={onClose}
        />
      </Space>
    </div>
  );

  return (
    <Card 
      className="chat-panel"
      title={renderHeader()}
      bodyStyle={{ padding: 0, height: '440px' }}
    >
      <div className="chat-body">
        {/* 左侧线程列表 */}
        <div className="thread-sidebar">
          <div className="thread-sidebar-header">
            <h4>对话列表</h4>
          </div>
          <div className="thread-list">
            {threads.length === 0 ? (
              <Empty 
                description="暂无对话"
                image={Empty.PRESENTED_IMAGE_SIMPLE}
                style={{ marginTop: '40px' }}
              />
            ) : (
              <List
                size="small"
                dataSource={threads}
                renderItem={(thread) => (
                  <List.Item
                    key={thread.threadId}
                    className={`thread-item ${currentThread?.threadId === thread.threadId ? 'active' : ''}`}
                    onClick={() => {
                      onThreadChange(thread);
                    }}
                    actions={[
                      <Tooltip key="delete" title="删除对话">
                        <Button 
                          type="text" 
                          size="small" 
                          icon={<DeleteOutlined />}
                          danger
                          onClick={(e) => {
                            e.stopPropagation(); // 阻止冒泡到线程项
                            handleDeleteClick(e, thread.threadId);
                          }}
                          className="delete-button"
                        />
                      </Tooltip>
                    ]}
                  >
                    <List.Item.Meta
                      title={
                        <Text ellipsis style={{ fontSize: '13px' }}>
                          {thread.threadName || `对话 ${thread.threadId}`}
                        </Text>
                      }
                      description={
                        <Text type="secondary" style={{ fontSize: '11px' }}>
                          {new Date(thread.lastUsedAt || thread.createdAt).toLocaleDateString()}
                        </Text>
                      }
                    />
                  </List.Item>
                )}
              />
            )}
          </div>
        </div>

        {/* 右侧聊天区域 */}
        <div className="chat-area">
          {currentThread ? (
            <>
              {/* 聊天区域头部 */}
              <div className="chat-area-header">
                <h4 className="chat-area-title">{currentThread.threadName}</h4>
              </div>

              {/* 消息区域 */}
              <div className="messages-container">
                {loadingHistory ? (
                  <div className="loading-container">
                    <Spin tip="加载聊天记录..." />
                  </div>
                ) : (
                  <div className="messages-list">
                    {messages.map((message, index) => renderMessage(message, index))}
                    
                    {/* 流式消息显示 */}
                    {sending && currentStreamingMessage && (
                      <div className="message assistant streaming">
                        <div className="message-avatar">
                          <RobotOutlined />
                        </div>
                        <div className="message-content">
                          <div className="message-text">
                            <div 
                              className="markdown-content"
                              dangerouslySetInnerHTML={{ 
                                __html: marked.parse(currentStreamingMessage || '') 
                              }}
                            />
                          </div>
                          {streamingSources.length > 0 && (
                            <div className="message-sources">
                              <Text type="secondary" style={{ fontSize: '12px' }}>参考来源:</Text>
                              {streamingSources.map((source, idx) => (
                                <Text key={idx} code style={{ fontSize: '11px', margin: '2px' }}>
                                  {source.title}
                                </Text>
                              ))}
                            </div>
                          )}
                          <div className="typing-indicator">
                            <span></span>
                            <span></span>
                            <span></span>
                          </div>
                        </div>
                      </div>
                    )}
                    
                    <div ref={messagesEndRef} />
                  </div>
                )}
              </div>

              {/* 输入区域 */}
              <div className="input-container">
                <Space.Compact style={{ width: '100%' }}>
                  <TextArea
                    ref={inputRef}
                    value={inputMessage}
                    onChange={(e) => setInputMessage(e.target.value)}
                    onKeyPress={handleKeyPress}
                    placeholder="输入消息..."
                    autoSize={{ minRows: 1, maxRows: 3 }}
                    disabled={sending}
                  />
                  <Button
                    type="primary"
                    icon={<SendOutlined />}
                    onClick={sendMessage}
                    loading={sending}
                    disabled={!inputMessage.trim()}
                  >
                    发送
                  </Button>
                </Space.Compact>
              </div>
            </>
          ) : (
            <div className="empty-chat">
              <MessageOutlined />
              <p>请选择或创建一个对话开始聊天</p>
              <Button 
                type="primary" 
                icon={<PlusOutlined />}
                onClick={handleCreateThread}
                style={{ marginTop: '12px' }}
              >
                创建新对话
              </Button>
            </div>
          )}
        </div>
      </div>
    </Card>
  );
};

export default ChatPanel;